<?php

/**
 * 自动生成 MerUserService
 * 
 * Apps/Common/Service/MerUserService.class.php
 * admin @ 2015-06-12
 */

namespace Common\Service;

use Common\Service\MerDictionaryService;
use Common\Service\MerWxSettingService;

class MerUserService {

  const USER_ROLE = 5;
  const STATUS    = 8;
  
  const REG_FROM_PC             = 1 ;
  const REG_FROM_WAP            = 2 ;
  const REG_FROM_IOS            = 3 ;
  const REG_FROM_ANDROID        = 4 ;
  const REG_FROM_WINDOWS_PHONE  = 5 ;
  const REG_FROM_WECHAT         = 6 ;
  const REG_FROM_WEIBO          = 7 ;
  const REG_FROM_QQ             = 8 ;
  const REG_FROM_UNKNOW         = 99 ;


  var $reg_from = array(
    1 => 'pc' ,
    2 => 'wap' ,
    3 => 'ios' ,
    4 => 'android' ,
    5 => 'windows phone',
    6 => 'wechat' ,
    7 => 'weibo' ,
    8 => 'qq' ,
    99 => '未知',
  );
  
  
  var $provider = array(
    'wechat' => '微信',
    'qq'     => 'QQ',
    'weibo'  => '新浪微博',
  );
  
  private static $instance;

  public static function instance() {
    if (self::$instance == null) {
      $instance = new MerUserService ();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'username' => '',
      'password' => '',
      'phone' => '',
      'email' => '',
      'area' => 0,
      'points' => 0,
      'status' => 10,
      'create_date' => date('Y-m-d H:i:s'),
      'binding_date' => '',
      'email_verified' => 0,
      'phone_verified' => 0
    );
  }

  function get_by_id($id , $with_openid = FALSE ) {
    $Meruser = M('MerUser');
    if ( !$with_openid ) {
      $data = $Meruser->find($id);
    } else {
      $data = $Meruser
        ->field('mer_user.* , uo.provider , uo.provider_id , uo.nickname , uo.sex , uo.headimgurl , uo.subscribe , uo.openid , uo.wx_qrcode')
        ->where('mer_user.id = ' . $id)
        ->join('mer_user_openid uo on uo.user_id = mer_user.id' , 'left')
        ->find();
      //echo $data;
    }
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'pid' => '',
      'keyword' => '',
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'mer_id' => 0,
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
      'promote_num' => FALSE ,
      'provider_info' => FALSE
    );

    $config = extend($config, $default);

    $Meruser = M('MerUser');

    $where = array();

    if ( !empty( $config['keyword'] ) ) {
      $k = $config['keyword'];
      $where['_string'] = " u.id = '$k' or u.nickname like '%$k%' or u.truename like '%$k%' or u.phone = '%$k%'";
    }
    
    if (!empty($config ['status'])) {
      $where ['u.status'] = $config ['status'];
    }

    if (!empty($config ['mer_id'])) {
      $where ['u.mer_id'] = $config ['mer_id'];
    }
    
    if ( $config ['pid'] !== '' ) {
      $where ['u.pid'] = $config ['pid'];
    }
    
    $where['uo.subscribe'] = 1 ;
    
    if ($config ['count']) {
      return $Meruser
        ->alias('u')
        ->join('mer_user_openid uo on uo.user_id = u.id' , 'left')
        ->where($where)->count();
    } else {
      $order = 'u.' .$config ['sort'] . ' ' . $config ['order'];
      $limit = ($config ['page'] - 1) * $config ['page_size'] . ' , ' . $config ['page_size'];

      $field = 'u.* , uo.provider , uo.provider_id , uo.nickname , uo.sex , uo.headimgurl , uo.subscribe , uo.openid , uo.wx_qrcode';
      if ( $config['promote_num'] ) {
        $field .= ' , ( SELECT COUNT(mer_user.id) FROM mer_user LEFT JOIN mer_user_openid ON mer_user_openid.user_id = mer_user.id WHERE pid = u.id AND mer_user_openid.subscribe = 1 ) AS promote_num';
      }
      $data = $Meruser
        ->alias('u')
        ->field($field)
        ->join('mer_user_openid uo on uo.user_id = u.id' , 'left')
        ->where($where)
        ->limit($limit)
        ->order($order)
        ->select();
      //echo $Meruser->_sql();

      /*
      if ($data && $config ['provider_info']) {
        $data = $this->_get_provider_info($data);
      }
       * 
       */
      return $data ? $data : array();
    }
  }

  /**
   * 取第三方用户信息 及微信公众号详情
   *
   * @param type $data          
   * @return type
   */
  function _get_provider_info($data) {
    $MerUserOpenid = M('MerUserOpenid');
    $MerWxSetting = M('MerWxSetting');

    foreach ($data as $key => $row) {
      $provider_info = $MerUserOpenid
        ->field('muo.* , wx.wx_no , wx.type')
        ->alias('muo')
        ->join('mer_wx_setting wx on wx.id = muo.provider_id')
        ->where('user_id = %d', $row['id'])
        ->select();
      $data[$key]['provider_info'] = $provider_info;
      //print_r($provider_info); 
      foreach ($provider_info as $k => $r) {
        $wx_name = '';
        if ($r['provider'] == 'wechat') {
          $wx_data = $MerWxSetting
            ->alias('mws')
            ->field('concat( mws.wx_no , "(", sd.text , ")" ) as wx_name ')
            ->join('sys_dictionary sd on sd.id = mws.type')
            ->where('mws.id = %d', $r['provider_id'])
            ->find();
          //echo $MerWxSetting->_sql();
          $wx_name = $wx_data['wx_name'];
        }
        $data[$key]['provider_info'][$k]['wx_name'] = $wx_name;
      }
    }
    return $data;
  }

  function create($data, $is_ajax = true) {
    $Meruser = M('MerUser');
    $ret = $Meruser->add($data);
    if ($ret) {
      if ($is_ajax) {
        return ajax_arr('添加成功', TRUE, array(
          'id' => $ret
        ));
      } else {
        return $ret;
      }
    } else {
      if ($is_ajax) {
        return ajax_arr('添加失败', FALSE);
      } else {
        return 0;
      }
    }
  }
  
  /**
   * 从微信创建用户
   * @param type $mer_id //商户ID
   * @param type $wx_id  //微信ID
   * @param type $userinfo //从微信取来的用户信息
   * @param type $pid    //推荐人ID
   * @return type
   */
  function create_by_wechat( $mer_id , $wx_id , $userinfo , $pid = 0 ) {
    $Meruser = M('MerUser');
    $MerUserOpenid = M('MerUserOpenid');
    
    $check_ret = $this->_openid_exists( $wx_id , 'wechat' , $userinfo , $pid );
    
    
    if ( $check_ret ) {
      //如果已经存在 且 已关注
      $check_ret['mer_id'] = $mer_id ;
      $check_ret['wx_id']  = $wx_id  ;
      
      return ajax_arr('已存在' , TRUE , array(
        'data' => $check_ret
      ));
    }
        
    //如果不存在 则添加
    $Meruser->startTrans();
    $data = array(
      'mer_id' => $mer_id ,
      'pid' => $pid ,
      'username' => 'gt_' . rand_string(12) ,
      'nickname' => $userinfo['nickname'] ,
      'password' => md5('123456') ,
      'reg_from' => self::REG_FROM_WECHAT , //注册来源
    );
    
    if ( $pid > 0 ) {
      $p_data = $this->get_by_id($pid);
      $data['group_id'] = $p_data['group_id'];
    }
    
    $user_id = $Meruser->add( $data );
    
    $openid_data = array(
      'user_id'     => $user_id ,
      'provider_id' => $wx_id  ,
      'openid'      => $userinfo['openid'] ,
      'nickname'    => $userinfo['nickname'] ,
      'sex'         => $userinfo['sex'] ,
      'headimgurl'  => $userinfo['headimgurl'] ,
      'subscribe'   => $userinfo['subscribe'] ,
    );
    
    $ret_openid = $MerUserOpenid->add( $openid_data );
    
    if( !$user_id || !$ret_openid ) {
      $Meruser->rollback();
      return ajax_arr('创建失败');
    } else {
      $Meruser->commit();
      $openid_data['ret_openid'] = $ret_openid ;
      $openid_data['pid'] = $pid ;
      return ajax_arr('创建成功' , TRUE , array(
        'data' => $openid_data
      ));
    }
  }
  
  /**
   * 检查openid 是否已经添加过了
   * @param type $provider_id
   * @param type $provider
   * @param type $openid
   * @return boolean
   */
  function _openid_exists( $provider_id , $provider = 'wechat', $userinfo = array() , $pid = 0 ) {
    $MerUserOpenid = M('MerUserOpenid');

    $where = array(
      'provider' => $provider ,
      'provider_id' => $provider_id ,
      'openid' => $userinfo['openid'] ,
    );
    
    $old_data = $MerUserOpenid
      ->field('mer_user_openid.* , mer_user.pid')
      ->where($where)
      ->join('mer_user on mer_user.id = mer_user_openid.user_id','left')
      ->find();
    //如果用户没有添加过
    if ( empty($old_data) ) {
      return FALSE ;
    }
    
    $MerUserOpenid->where($where)->save(array(
      'nickname' => $userinfo['nickname'] ,
      'headimgurl' => $userinfo['headimgurl'] ,
      'sex' => $userinfo['sex'] ,
      'subscribe' => $userinfo['subscribe'] 
    ));

    
    $check_pid = $this->get_by_id_pid($pid , $old_data['user_id']);
    //如果有推荐人 且之前没，则更新
    if( $pid > 0 && $old_data['pid'] == 0  && empty( $check_pid )) {
      $MerUser = M('MerUser');
      $MerUser->where('id = ' . $old_data['user_id'] )->save(array(
        'pid' => $pid 
      ));
    }
    
    return $old_data ;
  }
  
  function get_by_id_pid( $user_id , $pid ) {
    $MerUser = M('MerUser');
    $data = $MerUser->where('id = %d and pid = %d' , $user_id , $pid )->find();
    return $data ? $data : array() ;
  }

  /**
   * 微信取消订阅
   * @param type $mer_id
   * @param type $provider_id
   * @param type $provider
   * @param type $openid
   */
  function unfollow_openid( $mer_id , $provider_id , $provider = 'wechat', $openid = '' ) {
    $MerUserOpenid = M('MerUserOpenid');
    
    $where = array(
      'mer_id' => $mer_id ,
      'provider_id' =>$provider_id ,
      'provider' => $provider ,
      'openid' => $openid ,
    );
    
    $save_data = array(
      'subscribe' => 0 ,
    );
    $MerUserOpenid->where( $where )->save( $save_data );
  }
  

  function update($id, $data) {
    $Meruser = M('MerUser');

    $ret = $Meruser->where("id = %d", $id)
      ->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $Meruser = M('MerUser');
    $ret = $Meruser->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

  // 根据商户id和openid注册用户
  function reg_by_wx_mer_openid($mer_id, $openid, $pro_id, $provider = 'wechat') {
    // 先检查是否已经注册过了
    $MerUserOpenid = M('MerUserOpenid');
    $MerUser = M('MerUser');
    $check_data = $MerUserOpenid->where('provider = "wechat" and openid="%s"', $openid)
      ->find();
    if (!empty($check_data)) {
      // 用户已经关注过了
      $ret_data ['data'] = $MerUser->where('id = %d', $check_data ['user_id'])
        ->find();
      $ret_data ['data'] ['openid'] = $openid;
      return ajax_arr('注册用户成功(用户已存在)', TRUE, $ret_data);
    }

    $MerDictionary = MerDictionaryService::instance();
    $role_data = $MerDictionary->get_user_role($mer_id);
    $status_data = $MerDictionary->get_user_status($mer_id);

    // 先添加用户
    $user_data = array(
      'mer_id' => $mer_id,
      'username' => 'mer_' . $mer_id . '_' . rand_string(10),
      'password' => md5('123321'),
      'role_id' => key($role_data),
      'status' => key($status_data),
      'last_login' => date('Y-m-d H:i:s')
    );

    $ret = $MerUser->add($user_data);
    if (!$ret) {
      return ajax_arr('注册失败');
    }
    // 再添加openid关系表
    $user_openid_data = array(
      'user_id' => $ret,
      'provider' => $provider,
      'pro_id' => $pro_id,
      'openid' => $openid,
      'bind_time' => date('Y-m-d H:i:s')
    );
    $ret_bind = $MerUserOpenid->add($user_openid_data);
    if ($ret_bind) {
      $ret_data ['data'] = $user_data;
      $ret_data ['data'] ['openid'] = $openid;
      return ajax_arr('注册用户成功', TRUE, $ret_data);
    }
  }

  // 根据商户id和openid 取用户信息
  function get_by_mer_openid($mer_id, $openid) {
    $MerUser = M('MerUser');

    $where ['mu.mer_id'] = $mer_id;
    $where ['muo.openid'] = $openid;

    $data = $MerUser->field('mu.* , muo.openid')
      ->alias('mu')
      ->join('mer_user_openid muo on muo.user_id = mu.id')
      ->where($where)
      ->find();

    return $data ? $data : array();
  }

  // 根据商户id和openid 取用户信息
  function get_openid($id) {
    $MerUser = M('MerUser');
    $where ['u.id'] = $id;
    $data = $MerUser->field('muo.openid')
      ->field('u.* , uo.provider , uo.provider_id , uo.nickname , uo.sex , uo.headimgurl , uo.subscribe , uo.openid , uo.wx_qrcode')
      ->join('mer_user_openid uo on uo.user_id = u.id' , 'left')
      ->where($where)
      ->find();
    return $data ? $data ["openid"] : null;
  }

  // 根据商户id和openid 取用户信息
  function get_area_user_open_id($mer_id, $area) {
    $MerUser = M('MerUser');
    $where ['mu.mer_id'] = $mer_id;
    $where ['mu.area'] = $area;
    $data = $MerUser->field('muo.openid')
      ->alias('mu')
      ->join('mer_user_openid muo on muo.user_id = mu.id')
      ->where($where)
      ->select();
    return $data ? $data : array();
  }

  // 根据商户id和 phone 取用户信息
  function get_by_mer_phone($mer_id, $phone) {
    $MerUser = M('MerUser');

    $where ['mer_id'] = $mer_id;
    $where ['phone'] = $phone;

    $data = $MerUser->where($where)->find();
    return $data ? $data : array();
  }

  function find($where) {
    $MerUser = M('MerUser');
    $data = $MerUser->where($where)->find();
    return $data ? $data : array();
  }
  
  /**
   * 绑定openid到用户
   *
   * @param unknown $id          
   * @param unknown $openid          
   * @param number $mer_id          
   * @param string $provider          
   */
  function set_openid($id, $openid, $mer_id = 0, $provider = "wechat") {
    // if ($mer_id == 0) {
    // $MerUser = M ( 'MerUser' );
    // $mer_id = $MerUser->find ( $id )["mer_id"];
    // }
    $MerWxSettingService = MerWxSettingService::instance();
    $wx_setting = $MerWxSettingService->get_by_mer_id_and_type($mer_id, 31);
    $MerUserOpenid = M('MerUserOpenid');
    $MerUserOpenid->where(array(
        "user_id" => $id,
        "provider" => $provider,
        "pro_id" => $wx_setting ["id"]
      ))
      ->delete();
    $uo = $MerUserOpenid->where(array(
        "openid" => $openid,
        "provider" => $provider,
        "pro_id" => $wx_setting ["id"]
      ))
      ->find();
    $ret = FALSE;
    if (empty($uo)) {
      $ret = $MerUserOpenid->add(array(
        "user_id" => $id,
        "provider" => $provider,
        "openid" => $openid,
        "pro_id" => $wx_setting ["id"]
      ));
      // echo '创建---';
      // echo $MerUserOpenid->_sql ();
    } else {
      $ret = $MerUserOpenid->where(array(
          "id" => $uo ["id"]
        ))
        ->save(array(
        "user_id" => $id,
        "bind_time" => date("Y-m-d h:i:s", time())
      ));

      //echo $MerUserOpenid->_sql();
    }
    if ($ret) {
      return ajax_arr('綁定成功', TRUE);
    } else {
      return ajax_arr('綁定失败', FALSE);
    }
  }

  function create_wx_qrcode( $mer_id , $wx_id , $user_id ) {
    $WechatSdk = new WechatSdkService(  $mer_id , $wx_id );
    
    $wx_ret = $WechatSdk->getQRCode($user_id, 1);
    $url = $WechatSdk->getQRUrl($wx_ret['ticket']);
    
    $path = './Public/upload/wechat/' . date('Ym');
    if ( !file_exists($path) ) {
      mkdir($path, 0777) ;
    }
    
    $filename = $path . '/' . rand_string(16);
    $img_data = file_get_contents($url);
    file_put_contents($filename, $img_data);
    
    $MerUserOpenid = M('MerUserOpenid');
    $ret = $MerUserOpenid->where(array(
      'mer_id' => $mer_id ,
      'wx_id' => $wx_id ,
      'user_id' => $user_id ,
    ))->save( array(
      'wx_qrcode' => $filename ,
      'wx_url' => $wx_ret['url'],
    ) );
    if ( $ret === FALSE ) {
      return ajax_arr('生成失败'); 
    } else {
      return ajax_arr('生成成功' , TRUE ); 
    }
  }
}
